import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  SafeAreaView,
  StatusBar,
  TextInput,
  Modal,
  Alert,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import AsyncStorage from '@react-native-async-storage/async-storage';

// Simple text-based icons
const Icon = ({ name, size = 24, color = '#000' }: { name: string; size?: number; color?: string }) => {
  const iconMap: { [key: string]: string } = {
    'arrow-back': '⬅️',
    'add': '+',
    'arrow-down': '▼',
    'arrow-up': '▲',
    'calendar': '📅',
  };

  return (
    <Text style={{ fontSize: size, color, textAlign: 'center' }}>
      {iconMap[name] || '📱'}
    </Text>
  );
};

interface DropdownOption {
  label: string;
  value: string;
}

const XinziApplication: React.FC = () => {
  const navigation = useNavigation();
  const [formData, setFormData] = useState({
    applicant: '',
    department: '',
    position: '',
    currentSalary: '',
    proposedSalary: '',
    reason: '',
    effectiveDate: '',
  });

  // Dropdown states
  const [showDepartmentDropdown, setShowDepartmentDropdown] = useState(false);
  const [showPositionDropdown, setShowPositionDropdown] = useState(false);
  const [showDatePicker, setShowDatePicker] = useState(false);

  // Date picker state
  const [selectedYear, setSelectedYear] = useState(new Date().getFullYear());
  const [selectedMonth, setSelectedMonth] = useState(new Date().getMonth() + 1);

  // Dropdown options
  const departmentOptions: DropdownOption[] = [
    { label: '技术部', value: '技术部' },
    { label: '人事部', value: '人事部' },
    { label: '财务部', value: '财务部' },
    { label: '市场部', value: '市场部' },
    { label: '运营部', value: '运营部' },
  ];

  const positionOptions: DropdownOption[] = [
    { label: '技术员', value: '技术员' },
    { label: '工程师', value: '工程师' },
    { label: '高级工程师', value: '高级工程师' },
    { label: '技术主管', value: '技术主管' },
    { label: '技术经理', value: '技术经理' },
    { label: '人事专员', value: '人事专员' },
    { label: '财务专员', value: '财务专员' },
    { label: '市场专员', value: '市场专员' },
  ];

  const years = Array.from({ length: 5 }, (_, i) => new Date().getFullYear() + i);
  const months = Array.from({ length: 12 }, (_, i) => i + 1);

  const getDaysInMonth = (year: number, month: number) => {
    return new Date(year, month, 0).getDate();
  };

  const handleOptionSelect = (field: string, value: string) => {
    setFormData({ ...formData, [field]: value });
    setShowDepartmentDropdown(false);
    setShowPositionDropdown(false);
  };

  const handleDateSelect = (day: number) => {
    const formattedMonth = selectedMonth.toString().padStart(2, '0');
    const formattedDay = day.toString().padStart(2, '0');
    const newDate = `${selectedYear}-${formattedMonth}-${formattedDay}`;
    
    // 验证日期不能小于当前日期
    const selectedDate = new Date(selectedYear, selectedMonth - 1, day);
    const currentDate = new Date();
    currentDate.setHours(0, 0, 0, 0);
    
    if (selectedDate < currentDate) {
      Alert.alert('提示', '生效日期不能早于今天');
      return;
    }
    
    setFormData({ ...formData, effectiveDate: newDate });
    setShowDatePicker(false);
  };

  const validateForm = (): boolean => {
    if (!formData.applicant.trim()) {
      Alert.alert('提示', '请输入申请人姓名');
      return false;
    }
    if (!formData.department.trim()) {
      Alert.alert('提示', '请选择部门');
      return false;
    }
    if (!formData.position.trim()) {
      Alert.alert('提示', '请选择岗位');
      return false;
    }
    if (!formData.currentSalary.trim()) {
      Alert.alert('提示', '请输入当前薪资');
      return false;
    }
    if (!formData.proposedSalary.trim()) {
      Alert.alert('提示', '请输入调整后薪资');
      return false;
    }
    if (!formData.reason.trim()) {
      Alert.alert('提示', '请输入调整原因');
      return false;
    }
    if (!formData.effectiveDate.trim()) {
      Alert.alert('提示', '请选择生效日期');
      return false;
    }
    return true;
  };

  const saveToLocalStorage = async (data: any) => {
    try {
      const existingData = await AsyncStorage.getItem('applications');
      const applications = existingData ? JSON.parse(existingData) : [];
      
      const newApplication = {
        id: Date.now().toString(),
        type: '薪资调整',
        applicant: data.applicant,
        applicationTime: new Date().toLocaleString(),
        status: '等待审批',
        data: data,
      };
      
      applications.push(newApplication);
      await AsyncStorage.setItem('applications', JSON.stringify(applications));
    } catch (error) {
      console.error('保存失败:', error);
    }
  };

  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }
    
    await saveToLocalStorage(formData);
    Alert.alert('成功', '薪资调整申请已提交', [
      {
        text: '确定',
        onPress: () => (navigation as any).navigate('AllApplications'),
      },
    ]);
  };

  const renderDropdown = (
    visible: boolean,
    options: DropdownOption[],
    onSelect: (value: string) => void,
    onClose: () => void
  ) => (
    <Modal
      visible={visible}
      transparent={true}
      animationType="fade"
      onRequestClose={onClose}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={onClose}
      >
        <View style={styles.dropdownContainer}>
          <ScrollView style={styles.dropdownScroll}>
            {options.map((option, index) => (
              <TouchableOpacity
                key={index}
                style={styles.dropdownOption}
                onPress={() => onSelect(option.value)}
              >
                <Text style={styles.dropdownOptionText}>{option.label}</Text>
              </TouchableOpacity>
            ))}
          </ScrollView>
        </View>
      </TouchableOpacity>
    </Modal>
  );

  const renderDatePicker = () => (
    <Modal
      visible={showDatePicker}
      transparent={true}
      animationType="slide"
      onRequestClose={() => setShowDatePicker(false)}
    >
      <TouchableOpacity
        style={styles.modalOverlay}
        activeOpacity={1}
        onPress={() => setShowDatePicker(false)}
      >
        <View style={styles.datePickerContainer}>
          <View style={styles.datePickerHeader}>
            <Text style={styles.datePickerTitle}>选择生效日期</Text>
            <TouchableOpacity onPress={() => setShowDatePicker(false)}>
              <Text style={styles.confirmButton}>确定</Text>
            </TouchableOpacity>
          </View>
          
          <View style={styles.datePickerControls}>
            <View style={styles.yearMonthSelector}>
              <TouchableOpacity
                style={styles.selectorButton}
                onPress={() => setSelectedYear(prev => Math.max(prev - 1, new Date().getFullYear()))}
              >
                <Text style={styles.selectorButtonText}>◀</Text>
              </TouchableOpacity>
              <Text style={styles.yearMonthText}>{selectedYear}年</Text>
              <TouchableOpacity
                style={styles.selectorButton}
                onPress={() => setSelectedYear(prev => prev + 1)}
              >
                <Text style={styles.selectorButtonText}>▶</Text>
              </TouchableOpacity>
            </View>
            
            <View style={styles.yearMonthSelector}>
              <TouchableOpacity
                style={styles.selectorButton}
                onPress={() => setSelectedMonth(prev => prev > 1 ? prev - 1 : 12)}
              >
                <Text style={styles.selectorButtonText}>◀</Text>
              </TouchableOpacity>
              <Text style={styles.yearMonthText}>{selectedMonth}月</Text>
              <TouchableOpacity
                style={styles.selectorButton}
                onPress={() => setSelectedMonth(prev => prev < 12 ? prev + 1 : 1)}
              >
                <Text style={styles.selectorButtonText}>▶</Text>
              </TouchableOpacity>
            </View>
          </View>
          
          <View style={styles.daysGrid}>
            {Array.from({ length: getDaysInMonth(selectedYear, selectedMonth) }, (_, i) => i + 1).map(day => (
              <TouchableOpacity
                key={day}
                style={styles.dayButton}
                onPress={() => handleDateSelect(day)}
              >
                <Text style={styles.dayButtonText}>{day}</Text>
              </TouchableOpacity>
            ))}
          </View>
        </View>
      </TouchableOpacity>
    </Modal>
  );

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" backgroundColor="#fff" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton}
          onPress={() => navigation.goBack()}
        >
          <Icon name="arrow-back" size={20} color="#333" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>薪资调整申请</Text>
        <View style={styles.headerSpacer} />
      </View>

      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {/* Form */}
        <View style={styles.formContainer}>
          {/* Applicant */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>申请人</Text>
            <TextInput
              style={styles.input}
              value={formData.applicant}
              onChangeText={(text) => setFormData({ ...formData, applicant: text })}
              placeholder="请输入申请人姓名"
              placeholderTextColor="#999"
            />
          </View>

          {/* Department */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>部门</Text>
            <TouchableOpacity
              style={styles.dropdownButton}
              onPress={() => setShowDepartmentDropdown(true)}
            >
              <Text style={[
                styles.dropdownButtonText,
                !formData.department && { color: '#999' }
              ]}>
                {formData.department || '请选择部门'}
              </Text>
              <Icon name="arrow-down" size={16} color="#666" />
            </TouchableOpacity>
          </View>

          {/* Position */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>岗位</Text>
            <TouchableOpacity
              style={styles.dropdownButton}
              onPress={() => setShowPositionDropdown(true)}
            >
              <Text style={[
                styles.dropdownButtonText,
                !formData.position && { color: '#999' }
              ]}>
                {formData.position || '请选择岗位'}
              </Text>
              <Icon name="arrow-down" size={16} color="#666" />
            </TouchableOpacity>
          </View>

          {/* Current Salary */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>当前薪资</Text>
            <TextInput
              style={styles.input}
              value={formData.currentSalary}
              onChangeText={(text) => setFormData({ ...formData, currentSalary: text })}
              placeholder="请输入当前薪资"
              placeholderTextColor="#999"
              keyboardType="numeric"
            />
          </View>

          {/* Proposed Salary */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>调整后薪资</Text>
            <TextInput
              style={styles.input}
              value={formData.proposedSalary}
              onChangeText={(text) => setFormData({ ...formData, proposedSalary: text })}
              placeholder="请输入调整后薪资"
              placeholderTextColor="#999"
              keyboardType="numeric"
            />
          </View>

          {/* Effective Date */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>生效日期</Text>
            <TouchableOpacity
              style={styles.dropdownButton}
              onPress={() => setShowDatePicker(true)}
            >
              <Text style={[
                styles.dropdownButtonText,
                !formData.effectiveDate && { color: '#999' }
              ]}>
                {formData.effectiveDate || '请选择生效日期'}
              </Text>
              <Icon name="calendar" size={16} color="#666" />
            </TouchableOpacity>
          </View>

          {/* Reason */}
          <View style={styles.formGroup}>
            <Text style={styles.label}>调整原因</Text>
            <TextInput
              style={[styles.input, styles.textArea]}
              value={formData.reason}
              onChangeText={(text) => setFormData({ ...formData, reason: text })}
              placeholder="请输入薪资调整原因"
              placeholderTextColor="#999"
              multiline
              numberOfLines={4}
              textAlignVertical="top"
            />
          </View>

          {/* Submit Button */}
          <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
            <Text style={styles.submitButtonText}>提交申请</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>

      {/* Dropdowns */}
      {renderDropdown(
        showDepartmentDropdown,
        departmentOptions,
        (value) => handleOptionSelect('department', value),
        () => setShowDepartmentDropdown(false)
      )}
      
      {renderDropdown(
        showPositionDropdown,
        positionOptions,
        (value) => handleOptionSelect('position', value),
        () => setShowPositionDropdown(false)
      )}

      {/* Date Picker */}
      {renderDatePicker()}
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 16,
    backgroundColor: '#fff',
    borderBottomWidth: 1,
    borderBottomColor: '#e0e0e0',
  },
  backButton: {
    padding: 4,
  },
  headerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  headerSpacer: {
    width: 28,
  },
  content: {
    flex: 1,
    padding: 16,
  },
  formContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.1,
    shadowRadius: 3.84,
    elevation: 5,
  },
  formGroup: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginBottom: 8,
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 6,
    paddingHorizontal: 12,
    paddingVertical: 12,
    fontSize: 16,
    color: '#333',
    backgroundColor: '#fff',
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  dropdownButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 6,
    paddingHorizontal: 12,
    paddingVertical: 12,
    backgroundColor: '#fff',
  },
  dropdownButtonText: {
    fontSize: 16,
    color: '#333',
    flex: 1,
  },
  submitButton: {
    backgroundColor: '#2196F3',
    borderRadius: 6,
    paddingVertical: 16,
    alignItems: 'center',
    marginTop: 20,
  },
  submitButtonText: {
    color: '#fff',
    fontSize: 18,
    fontWeight: '600',
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  dropdownContainer: {
    backgroundColor: '#fff',
    borderRadius: 8,
    maxHeight: 300,
    width: '80%',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  dropdownScroll: {
    maxHeight: 300,
  },
  dropdownOption: {
    paddingVertical: 16,
    paddingHorizontal: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  dropdownOptionText: {
    fontSize: 16,
    color: '#333',
  },
  datePickerContainer: {
    backgroundColor: '#fff',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    padding: 20,
    width: '100%',
    maxHeight: '80%',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.84,
    elevation: 5,
  },
  datePickerHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
    paddingBottom: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#f0f0f0',
  },
  datePickerTitle: {
    fontSize: 18,
    fontWeight: '600',
    color: '#333',
  },
  confirmButton: {
    fontSize: 16,
    color: '#6c5ce7',
    fontWeight: '600',
  },
  datePickerControls: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginBottom: 20,
  },
  yearMonthSelector: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectorButton: {
    padding: 8,
  },
  selectorButtonText: {
    fontSize: 16,
    color: '#2196F3',
    fontWeight: '600',
  },
  yearMonthText: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
    marginHorizontal: 12,
  },
  daysGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
  },
  dayButton: {
    width: '13%',
    aspectRatio: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: 8,
    borderRadius: 6,
    backgroundColor: '#f0f0f0',
  },
  dayButtonText: {
    fontSize: 16,
    color: '#333',
  },
});

export default XinziApplication;
